package com.pcbly.web.persistence.mail;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.pcbly.web.Constants;
import com.pcbly.web.bean.mail.UserReceiveMailBean;
import com.pcbly.web.bean.mail.UserReceiveMainBean;
import com.pcbly.web.components.hibernate.support.Page;
import com.pcbly.web.components.utils.LightsoftStringUtils;
import com.pcbly.web.persistence.HibernateBaseDao;

@SuppressWarnings("unchecked")
public class UserReceiveMainHibernateDao extends
		HibernateBaseDao<UserReceiveMainBean> implements UserReceiveMainDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = 306218346860754269L;

	protected Class<UserReceiveMainBean> getEntityClass() {
		return UserReceiveMainBean.class;
	}

	public UserReceiveMainHibernateDao() {
		super();
	}

	public void createUserReceiveMain(UserReceiveMainBean bean) {
		Session session = getSession(false);
		StringBuilder sb = new StringBuilder();
		sb.append("insert into ");
		session.createSQLQuery("");
	}

	private void setUserMailBeans(List<UserReceiveMailBean> userMailBeans,
			Set<UserReceiveMailBean> froms, String userName, String main) {
		if (froms != null && !froms.isEmpty())
			for (UserReceiveMailBean from : froms) {
				if (!(from.getMail().equals(userName))) {
					// from.setId((new GUID()).toString());
					from.setMainId(main); 
					userMailBeans.add(from);
				}
			}
	}

	@Override
	public int saveList(final List<UserReceiveMainBean> list,
			final String userName) throws Exception {
		final List<UserReceiveMainBean> mainBeans = new ArrayList<UserReceiveMainBean>();
		for (UserReceiveMainBean bean : list) {
			Set<UserReceiveMailBean> froms = bean.getFroms();
			Set<UserReceiveMailBean> fromTos = bean.getFromTos();
			Set<UserReceiveMailBean> fromCCs = bean.getFromCCs();
			Set<UserReceiveMailBean> fromBCCs = bean.getFromBCCs();
			List<UserReceiveMailBean> userMailBeans = new ArrayList<UserReceiveMailBean>();
			boolean iflag = false;
			for (UserReceiveMailBean from : froms) {
				if (from.getMail().equals(userName)) {
					iflag = true;
					break;
				}
			}
			if (iflag) {
				bean.setFlag(Constants.EMAIL_FLAG_BOX_SEND);
			} else {
				bean.setFlag(Constants.EMAIL_FLAG_BOX_RECIEVE);
			}
			setUserMailBeans(userMailBeans, froms, userName, bean.getId());
			setUserMailBeans(userMailBeans, fromTos, userName, bean.getId());
			setUserMailBeans(userMailBeans, fromCCs, userName, bean.getId());
			setUserMailBeans(userMailBeans, fromBCCs, userName, bean.getId());
			if (userMailBeans!=null&&!userMailBeans.isEmpty()) {
				bean.getUserReceiveMailBeans().addAll(userMailBeans);
			} 
			mainBeans.add(bean);

		}
		// TODO Auto-generated method stub
		Integer tr = (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						// TODO Auto-generated method stub
						Integer tr = 0;
						try {
							for (UserReceiveMainBean bean : mainBeans) {
								session.save(bean);
							}
							tr = 1;
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e.getMessage());
						}
						return tr;
					}
				});
		return tr;
	}

	
	@Override
	public Page<UserReceiveMainBean> findUserReceiveMainBeanByCond(
			UserReceiveMainBean bean, Page<UserReceiveMainBean> page,
			String orderByName, boolean asc) throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("select * from T_USER_MAIN where RECYCLED=0 ");
		if(!(bean==null)){
			if(bean.getFlag()>0){
				sb.append(" and BOXFLAG_ in (");
				sb.append(bean.getFlag());
				sb.append(",");
				sb.append(Constants.EMAIL_FLAG_BOX_DRAFT);
				sb.append(")");
			}else{
				sb.append(" and BOXFLAG_ in (");
				sb.append(Constants.EMAIL_FLAG_BOX_RECIEVE);
				sb.append(",");
				sb.append(Constants.EMAIL_FLAG_BOX_DRAFT);
				sb.append(")");
			}
			if(!LightsoftStringUtils.nullOrBlank(bean.getUserMailId())){
				sb.append(" and USERMAILID='");
				sb.append(bean.getUserMailId());
				sb.append("' ");
			}
		}
		if(!LightsoftStringUtils.nullOrBlank(orderByName)){
			if(asc){
				sb.append(" order by ");
				sb.append(orderByName);
				sb.append(" ");
			}else{
				sb.append(" order by ");
				sb.append(orderByName);
				sb.append(" desc ");
			}
		}
		if(logger.isDebugEnabled()){
			logger.debug("asc ::::::::::::::::::"+asc);
			logger.debug("orderByName ::::::::::::::::::"+orderByName);
			logger.debug("sql ::::::::::::::::::"+sb.toString());
			System.out.println("asc ::::::::::::::::::"+asc);
			System.out.println("orderByName ::::::::::::::::::"+orderByName);
			System.out.println("sql ::::::::::::::::::"+sb.toString());
		}
		Object obj = getSession().createSQLQuery(
				"select count(*)  " + removeSelect(removeOrders(sb.toString())) + " ").uniqueResult();
		if (obj == null) {
			obj = "0";
		}
		
		page.setTotalCount(Integer.parseInt(String.valueOf(obj)));
		
		if(page.getTotalCount()<1){
			return page;
		}
		
		int first = page.getFirst();
		int lpage = first + page.getPageSize();
		if (lpage > page.getTotalCount()) {
			lpage = page.getTotalCount();
		}
		List<UserReceiveMainBean> userReceiveMainBeans=getSession().createSQLQuery(
				sb.toString()).addEntity(UserReceiveMainBean.class).list().subList(first, lpage);
		
		page.setResult(userReceiveMainBeans);
		return page;
	}

	@Override
	public void removeComplateUserReceiveMainBeanById(String id)
			throws Exception {
		// TODO Auto-generated method stub
		if(logger.isDebugEnabled()){
			logger.debug(id);
		}
		StringBuilder sb=new StringBuilder();
		sb.append("update T_USER_MAIN set RECYCLED='1' where ID in('");
		id=id.replaceAll(",", "','");
		sb.append(id).append("') ");
		getSession().createSQLQuery(sb.toString()).executeUpdate();
	}

	@Override
	public void removeUserReceiveMainBeanById(String id) throws Exception {
		// TODO Auto-generated method stub
		if(logger.isDebugEnabled()){
			logger.debug(id);
		}
		StringBuilder sb=new StringBuilder();
		sb.append("update T_USER_MAIN set BOXFLAG_=");
		sb.append(Constants.EMAIL_FLAG_BOX_DELETE);
		sb.append(" where ID in('");
		id=id.replaceAll(",", "','");
		sb.append(id).append("') ");
		getSession().createSQLQuery(sb.toString()).executeUpdate();
	}

}
